package com.gzhryc.shared_device.oem.micro.iot.controllers;

import com.gzhryc.common.IDTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.api.DefaultAPICodeConstants;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.cdb.api.protocol.*;
import com.gzhryc.shared_device.cdb.code.services.models.CDBForceEjectSlotCacheData;
import com.gzhryc.shared_device.cdb.core.ICDBNetworkService;
import com.gzhryc.shared_device.cdb.core.models.CDBExecuteResult;
import com.gzhryc.shared_device.cdb.core.models.CDBLeaseCommand;
import com.gzhryc.shared_device.oem.code.device.CDBCacheManager;
import com.gzhryc.shared_device.oem.micro.iot.LocalNetworkServiceUtils;
import com.gzhryc.shared_device.oem.micro.iot.MicroConstants;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CDBOperateController {

    static Logger log = Logger.getLogger(CDCZOperateController.class);

    @Route(value = {"/api/v1/cdb/lease.do"}, method = "POST")
    public CDBHttpLeaseResponse lease(HttpServletRequest request, HttpServletResponse response) {
        CDBHttpLeaseResponse apiResp = new CDBHttpLeaseResponse(DefaultAPICodeConstants.EXECUTE_ERROR,"操作失败，请稍后再试");
        CDBHttpLeaseRequest apiReq = WebUtils.getJsonRequest(request, CDBHttpLeaseRequest.class);
        if (apiReq != null && StringTools.isNotBlank(apiReq.getBody().getDeviceSn())) {
            Long iotId = WebUtils.getAttribute(request, MicroConstants.ATTR_IOT_ID, Long.class);
            log.info("{{0}}IOT节点触发充电宝租借，请求：{{1:json}}",iotId,apiReq);
            ICDBNetworkService networkService = LocalNetworkServiceUtils.getCDBNetworkService(iotId);
            if (networkService != null) {
                CDBLeaseCommand leaseCommand = new CDBLeaseCommand();
                leaseCommand.setDeviceSn(apiReq.getBody().getDeviceSn());
                leaseCommand.setSlotNum(apiReq.getBody().getSlotNum());
                leaseCommand.setTradeNo(apiReq.getBody().getTradeNo());

                CDBExecuteResult executeResult = networkService.lease(leaseCommand);
                if (executeResult != null) {
                    apiResp.setCode(DefaultAPICodeConstants.SUCCESS, null);
                    apiResp.getBody().setResultCode(executeResult.getCode());
                    apiResp.getBody().setErrorMsg(executeResult.getMsg());
                    apiResp.getBody().setMessageId(executeResult.getMessageId());
                }
            } else {
                apiResp.setMsg("未找到共享充电宝网络服务");
            }
        }
        return apiResp;
    }

    @Route(value = {"/api/v1/cdb/eject.do"}, method = "POST")
    public CDBHttpEjectResponse eject(HttpServletRequest request, HttpServletResponse response) {
        CDBHttpEjectResponse apiResp = new CDBHttpEjectResponse(DefaultAPICodeConstants.EXECUTE_ERROR,"操作失败，请稍后再试");
        CDBHttpEjectRequest apiReq = WebUtils.getJsonRequest(request, CDBHttpEjectRequest.class);
        if (apiReq != null && StringTools.isNotBlank(apiReq.getBody().getDeviceSn())) {
            Long iotId = WebUtils.getAttribute(request, MicroConstants.ATTR_IOT_ID, Long.class);
            if(apiReq.getBody().getSlotNum() != null){
                log.info("{{0}}IOT节点触发充电宝强制弹出，请求：{{1:json}}",iotId,apiReq);
                ICDBNetworkService networkService = LocalNetworkServiceUtils.getCDBNetworkService(iotId);
                if (networkService != null) {
                    CDBForceEjectSlotCacheData ejectSlotCacheData = new CDBForceEjectSlotCacheData();
                    ejectSlotCacheData.setDeviceSn(apiReq.getBody().getDeviceSn());
                    ejectSlotCacheData.setSlotNum(apiReq.getBody().getSlotNum());
                    String messageId =  apiReq.getBody().getMessageId();
                    if(StringTools.isBlank(messageId)){
                        messageId = IDTools.getTimestampSecondID();
                    }
                    CDBCacheManager.self().setCommandResult(ejectSlotCacheData.getDeviceSn(),messageId,JsonTools.toJson(ejectSlotCacheData));

                    CDBExecuteResult executeResult = networkService.forceEjectDevice(apiReq.getBody().getDeviceSn(),apiReq.getBody().getSlotNum(),messageId);
                    if (executeResult != null) {
                        apiResp.setCode(DefaultAPICodeConstants.SUCCESS, null);
                        apiResp.getBody().setResultCode(executeResult.getCode());
                        apiResp.getBody().setErrorMsg(executeResult.getMsg());
                        apiResp.getBody().setMessageId(executeResult.getMessageId());
                    }
                } else {
                    apiResp.setMsg("未找到共享充电宝网络服务");
                }
            }else{
                log.info("{{0}}IOT节点触发充电宝全部弹出，请求：{{1:json}}",iotId,apiReq);
                ICDBNetworkService networkService = LocalNetworkServiceUtils.getCDBNetworkService(iotId);
                if (networkService != null) {
                    CDBForceEjectSlotCacheData ejectSlotCacheData = new CDBForceEjectSlotCacheData();
                    ejectSlotCacheData.setDeviceSn(apiReq.getBody().getDeviceSn());
                    String messageId =  apiReq.getBody().getMessageId();
                    if(StringTools.isBlank(messageId)){
                        messageId = IDTools.getTimestampSecondID();
                    }
                    CDBCacheManager.self().setCommandResult(ejectSlotCacheData.getDeviceSn(),messageId,JsonTools.toJson(ejectSlotCacheData));

                    CDBExecuteResult executeResult = networkService.forceEjectDevice(apiReq.getBody().getDeviceSn(),messageId);
                    if (executeResult != null) {
                        apiResp.setCode(DefaultAPICodeConstants.SUCCESS, null);
                        apiResp.getBody().setResultCode(executeResult.getCode());
                        apiResp.getBody().setErrorMsg(executeResult.getMsg());
                        apiResp.getBody().setMessageId(executeResult.getMessageId());
                    }
                } else {
                    apiResp.setMsg("未找到共享充电宝网络服务");
                }
            }
        }
        return apiResp;
    }

    @Route(value = {"/api/v1/cdb/search.do"}, method = "POST")
    public CDBHttpSearchResponse search(HttpServletRequest request, HttpServletResponse response) {
        CDBHttpSearchResponse apiResp = new CDBHttpSearchResponse(DefaultAPICodeConstants.EXECUTE_ERROR, "操作失败，请稍后再试");
        CDBHttpSearchRequest apiReq = WebUtils.getJsonRequest(request, CDBHttpSearchRequest.class);
        if (apiReq != null && StringTools.isNotBlank(apiReq.getBody().getDeviceSn())) {
            Long iotId = WebUtils.getAttribute(request, MicroConstants.ATTR_IOT_ID, Long.class);
            log.info("{{0}}IOT节点触发充电宝查询，请求：{{1:json}}", iotId, apiReq);
            ICDBNetworkService networkService = LocalNetworkServiceUtils.getCDBNetworkService(iotId);
            if (networkService != null) {
                CDBExecuteResult executeResult = networkService.searchDevice(apiReq.getBody().getDeviceSn());
                if (executeResult != null) {
                    apiResp.setCode(DefaultAPICodeConstants.SUCCESS, null);
                    apiResp.getBody().setResultCode(executeResult.getCode());
                    apiResp.getBody().setErrorMsg(executeResult.getMsg());
                    apiResp.getBody().setMessageId(executeResult.getMessageId());
                }
            } else {
                apiResp.setMsg("未找到共享充电宝网络服务");
            }
        }
        return apiResp;
    }

    @Route(value = {"/api/v1/cdb/send_cmd.do"}, method = "POST")
    public CDBHttpSendCmdResponse sendCmd(HttpServletRequest request, HttpServletResponse response) {
        CDBHttpSendCmdResponse apiResp = new CDBHttpSendCmdResponse(DefaultAPICodeConstants.EXECUTE_ERROR, "操作失败，请稍后再试");
        CDBHttpSendCmdRequest apiReq = WebUtils.getJsonRequest(request, CDBHttpSendCmdRequest.class);
        if (apiReq != null && StringTools.isNotBlank(apiReq.getBody().getDeviceSn()) && StringTools.isNotBlank(apiReq.getBody().getContent())) {
            Long iotId = WebUtils.getAttribute(request, MicroConstants.ATTR_IOT_ID, Long.class);
            log.info("{{0}}IOT节点触发充电宝任意报文，请求：{{1:json}}", iotId, apiReq);
            ICDBNetworkService networkService = LocalNetworkServiceUtils.getCDBNetworkService(iotId);
            if (networkService != null) {
                CDBExecuteResult executeResult = networkService.sendCmd(apiReq.getBody().getDeviceSn(),apiReq.getBody().getContent());
                if (executeResult != null) {
                    apiResp.setCode(DefaultAPICodeConstants.SUCCESS, null);
                    apiResp.getBody().setResultCode(executeResult.getCode());
                    apiResp.getBody().setErrorMsg(executeResult.getMsg());
                    apiResp.getBody().setMessageId(executeResult.getMessageId());
                }
            } else {
                apiResp.setMsg("未找到共享充电宝网络服务");
            }
        }
        return apiResp;
    }
}
